// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;

namespace SnapObjects.Data.AspNetCore
{
    internal class DataPackerXmlOutputFormatter : XmlOutputFormatter
    {
        protected override bool CanWriteType(Type type)
        {
            if (typeof(IDataPacker).IsAssignableFrom(type))
            {
                return base.CanWriteType(type);
            }

            return false;
        }
        public override async Task WriteResponseBodyAsync(
            OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var response = context.HttpContext.Response;

            var xml = String.Empty;

            if (context.Object is IDataPacker dataPacker)
            {
                xml = dataPacker.GetTextString(DataFormat.Xml);
            }

            await response.WriteAsync(xml);
        }
    }
}
